import { addServeUser, apiInterceptors, updateUser } from '@/client/api';
import { useRequest } from 'ahooks';
import { App, Form, Input, Modal, Spin } from 'antd';
import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useRouter } from 'next/router';
import styles from './styles.module.css';

interface CreateUserModalProps {
  open: boolean;
  onCancel: () => void;
  refresh?: () => Promise<void>;
  type?: 'add' | 'edit';
}

const CreateUserModal: React.FC<CreateUserModalProps> = ({ 
  open, 
  onCancel, 
  type = 'add', 
  refresh 
}) => {
  const { t } = useTranslation();
  const { message } = App.useApp();
  const [form] = Form.useForm();
  const userInfo = JSON.parse(localStorage.getItem('edit_user_info') || '{}');

  const formItems = useMemo(() => {
    const EMAIL_REGEX = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
    const PHONE_REGEX = /^1[3-9]\d{9}$/;
    const USERNAME_REGEX = /^[A-Za-z0-9_]{4,30}$/;

    const baseItems = [
      {
        name: 'login_name',
        label: t('user_name'),
        rules: [{ required: true, message: t('user_name_required') }],
        required: true,
      },
      {
        name: 'nick_name',
        label: t('user_nickname'),
        rules: [{ required: true, message: t('user_nickname_required') }],
        required: true,
      },
      // 根据类型动态控制密码字段
      ...(type === 'add' ? [{
        name: 'password',
        label: t('user_password'),
        rules: [{ required: true, message: t('user_password_required') }],
        required: true,
      }] : []),
      {
        name: 'email',
        label: t('user_email'),
        rules: [{ required: true, message: t('user_email_required') },{
          pattern: EMAIL_REGEX,
          message: t('email_format_error')
        }],
        required: true,
      },
      {
        name: 'telephone',
        label: t('user_number'),
        rules: [{ required: true, message: t('user_number_required') },{
          pattern: PHONE_REGEX,
          message: t('phone_format_error')
        }],
        required: true,
      },
    ];
    return baseItems;
  }, [t, type]); // 添加 type 作为依赖项

  const { run: createUser, loading: isSubmitting } = useRequest(
    async (params: any) => {
      if (type === 'edit') {
        const [error] = await apiInterceptors(updateUser({ ...params, avatar:'',id:userInfo.id }));
        if (error) throw error;
      }else {
        const [error] = await apiInterceptors(addServeUser({ ...params, avatar:''}));
        if (error) throw error;
      }
      
      return params;
    },
    {
      manual: true,
      onSuccess: async (data) => {
        if (type === 'edit') {
          message.success(t('update_success'));
        } else {
          message.success(t('create_success'));
        }
        await refresh?.();
        onCancel();
      },
      onError: () => {
        message.error(t(type === 'edit' ? 'update_failed' : 'create_failed'));
      },
    }
  );
  
  return (
    <Modal
      className={styles['modal-container']}
      title={t(type === 'edit' ? 'edit_user' : 'create_user')}
      width={800}
      open={open}
      okButtonProps={{ disabled: isSubmitting }}
      onOk={async () => {
        try {
          const values = await form.validateFields();
          await createUser(values);
        } catch (error) {
          console.error('Submission error:', error);
        }
      }}
      onCancel={onCancel}
      
      centered
    >
      <Spin spinning={isSubmitting}>
        <Form form={form} initialValues={userInfo} labelAlign="right" className='w-4/5'>
          {formItems.map(({ name, label, rules }) => (
            <Form.Item required labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} key={name} name={name} label={label} rules={rules}>
              <Input maxLength={30} placeholder={label} autoComplete="off" />
            </Form.Item>
          ))}
        </Form>
      </Spin>
    </Modal>
  );
};

export default CreateUserModal;

